#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <unistd.h>

using namespace std;

const char* pathname = "/home/lw/storehouse/process_communication";
const int proj_id = 0x66;

// 将key转化为16进制，方便与ipcs -m 查看的信息对比
string ItoH(int x)
{
    char buffer[1024];

    snprintf(buffer, sizeof(buffer), "0x%x", x);
    return buffer;
}

// 封装ftok，获取key
key_t GetKey()
{
    key_t k = ftok(pathname, proj_id);
    if(k < 0)
    {
        printf("get key fail, errno is %d, errstr is %s\n", errno, strerror(errno));
        exit(errno);
    }

    return k;
}

// 封装shmget，获取shmid
int _CreateShm(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if(shmid < 0)
    {
        printf("shmget fail, errno is %d, errstr is %s\n", errno, strerror(errno));
        exit(errno);
    }
    return shmid;
}

// 给服务器端提供，创建共享内存，已存在出错返回
int CreateShm(key_t key, int size)
{
    return _CreateShm(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

// 给客户端提供，获取服务端创建的共享内存的shmid
int GetShm(key_t key, int size)
{
    return _CreateShm(key, size, IPC_CREAT);
}

// 封装shmctl，删除共享内存
void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if(n < 0)
    {
        printf("DeleteShm fail, errno is %d, errstr is %s\n", errno, strerror(errno));
        exit(errno);
    }
}

// 封装shmat，挂接共享内存
void* ShmAttach(int shmid)
{
    void* shmaddr = shmat(shmid, nullptr, 0);
    if((long)shmaddr == -1)
    {
        printf("shm attach fail, errno is %d, errstr is %s\n", errno, strerror(errno));
        exit(errno);
    }
    return shmaddr;
}

// 封装shmdt，去挂接共享内存
void ShmDetach(const void* shmaddr)
{
    int n = shmdt(shmaddr);
    if(n == -1)
    {
        printf("shm detach fail, errno is %d, errstr is %s\n", errno, strerror(errno));
        return;
    }
}